package com.xinjixian.webgame;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;

import androidx.annotation.NonNull;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SaveImage {

    /**
     * view截图
     *
     * @return
     */
    public static void viewShot(@NonNull final View v, MainActivity activity) {
        if (null == v) {
            Log.e("SaveImage", "view is null");
            return;
        }
        Log.e("SaveImage", "getViewTreeObserver");
        v.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    v.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                } else {
                    v.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
                DisplayMetrics metrics = new DisplayMetrics();
                activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
                int height = metrics.heightPixels;
                int width = metrics.widthPixels;
                // 核心代码start
                Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
                Canvas c = new Canvas(bitmap);
                v.layout(0, 0, width, height);
                v.draw(c);
                // end
                Log.e("SaveImage", "getViewTreeObserver  END");
                String savePath = "";
                if (TextUtils.isEmpty(savePath)) {
                    savePath = createImagePath();
                }
                try {
                    compressAndGenImage(bitmap, savePath);
                    activity.showTips(bitmap);
                    Log.e("SaveImage", "--->截图保存地址：" + savePath);
                    // 最后通知图库更新
                    String path = Environment.getExternalStorageDirectory().getPath();
                    v.getContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private static final String IMAGE_FILE_NAME_TEMPLATE = "Image%s.jpg";
    private static final String IMAGE_FILE_PATH_TEMPLATE = "%s/%s";

    /**
     * 存储到sdcard
     *
     * @param bmp
     * @param maxSize 为0不压缩
     * @return
     */
    public static String saveToSD(Bitmap bmp, int maxSize) {
        if (bmp == null) {
            Log.e("SaveImage", "saveToSD--->bmp is null");
            return "";
        }
        //判断sd卡是否存在
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //文件名
            long systemTime = System.currentTimeMillis();
            String imageDate = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date(systemTime));
            String mFileName = String.format(IMAGE_FILE_NAME_TEMPLATE, imageDate);

            //文件全名
            File directory_doc = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
            String mstrRootPath = directory_doc.getPath();
            String filePath = String.format(IMAGE_FILE_PATH_TEMPLATE, mstrRootPath, mFileName);

            Log.e("SaveImage", "saveToSD--->file path:" + filePath);
            File file = new File(filePath);
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            Log.e("SaveImage", "saveToSD--->file AbsolutePath:" + filePath);
            try {
                compressAndGenImage(bmp, filePath, maxSize);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                bmp.recycle();
            }

            return filePath;
        }
        return "";
    }

    public static String createImagePath() {
        //判断sd卡是否存在
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //文件名
            long systemTime = System.currentTimeMillis();
            String imageDate = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date(systemTime));
            String mFileName = String.format(IMAGE_FILE_NAME_TEMPLATE, imageDate);

            //文件全名
            File directory_doc = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
            String mstrRootPath = directory_doc.getPath();
            String filePath = String.format(IMAGE_FILE_PATH_TEMPLATE, mstrRootPath, mFileName);
            File file = new File(filePath);
            //获取内部存储状态
            String state = Environment.getExternalStorageState();
            //如果状态不是mounted，无法读写
            if (!state.equals(Environment.MEDIA_MOUNTED)) {
                Log.e("SaveImage", "--->无法读写：");
            }

            if (!file.exists()) {
                try {
                    File file1 = new File(mstrRootPath);
                    file1.mkdir();
                    file.createNewFile();
                    Log.e("SaveImage", "--->createNewFile：");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return filePath;
        }
        return "";
    }

    public static void compressAndGenImage(Bitmap image, String outPath, int maxSize) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        // scale
        int options = 100;
        // Store the bitmap into output stream(no compress)
        image.compress(Bitmap.CompressFormat.JPEG, options, os);
        // Compress by loop
        if (maxSize != 0) {
            while (os.toByteArray().length / 1024 > maxSize) {
                // Clean up os
                os.reset();
                // interval 10
                options -= 10;
                image.compress(Bitmap.CompressFormat.JPEG, options, os);
            }
        }

        // Generate compressed image file
        FileOutputStream fos = new FileOutputStream(outPath);
        fos.write(os.toByteArray());
        Log.e("SaveImage", "compressAndGenImage--->文件大小：" + os.size() + "，压缩比例：" + options);
        fos.flush();
        fos.close();
    }

    public static void compressAndGenImage(Bitmap image, String outPath) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        // scale
        int options = 70;
        // Store the bitmap into output stream(no compress)
        image.compress(Bitmap.CompressFormat.JPEG, options, os);

        // Generate compressed image file
        FileOutputStream fos = new FileOutputStream(outPath);
        fos.write(os.toByteArray());
        Log.e("SaveImage", "compressAndGenImage--->文件大小：" + os.size() + "，压缩比例：" + options);
        fos.flush();
        fos.close();
    }
}
